package com.example.springbootexam.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.springbootexam.bean.User;
import com.example.springbootexam.bean.UserInfo;
import com.example.springbootexam.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/8/12
 * Email haijunzhou@hnit.edu.cn
 */
@Service
public class UserBiz {

    @Autowired
    UserMapper userMapper;

    public void reg(User user) throws BizExeption {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName, user.getName());
        if (userMapper.exists(lqw)) {
            throw new BizExeption("该账号已注册!","name");
        }

        lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone, user.getPhone());
        if (userMapper.exists(lqw)) {
            throw new BizExeption("该手机号码已注册!","phone");
        }
        userMapper.insert(user);
    }

    public User login(User user) throws BizExeption {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getName,user.getName());
        if (userMapper.exists(lqw)==false) {
            throw new BizExeption("该账号还没有注册!","name");
        }
        lqw.eq(User::getName, user.getName());
        lqw.eq(User::getPwd, user.getPwd());
        User dbUser = userMapper.selectOne(lqw);
        if(dbUser == null){
            throw new BizExeption("用户名或密码错误!","pwd");
        }
        return dbUser;
    }

    public void updatePwd(UserInfo updateUser) throws BizExeption {
        User user = new User();
        user.setId(updateUser.getId());
        user.setPwd(updateUser.getRepwd());
        int ret = userMapper.updateById(user);
        if(ret <= 0){
            throw new BizExeption("修改密码失败!","pwd");
        }
    }
}
